<script setup lang="ts">
import {
  ElButton, ElForm, ElMessage, FormInstance, FormRules,
  ElFormItem, ElInput, ElSelect, ElOption,
  ElCheckboxGroup, ElCheckbox,
} from 'element-plus';
import { ref, reactive, computed } from 'vue';
import {initPoint, RegionPoint} from '../right/RegionEditDialog.vue';
import {latBreakDown, lonBreakDown} from 'common/src/utils/lnglat';
import {
  intervalOptions,
  forecastOptions,
  sourceOptions,
  resolutionOptions,
  weatherOptions,
} from '../right/WeatherSelectDialog.vue';
import {getTaskPack, TaskItem} from '@/services/task';
import {routeOptions, TaskType} from 'common/src/utils/special';

interface Props {
  task?: TaskItem;
  /** 可选航线类型列表，如 [1,2,5] */
  routeType?: number[];
}

interface WeatherConfig {
  topLeft: RegionPoint;
  bottomRight: RegionPoint;
  interval: number;
  forecast: number;
  source: string;
  resolution: number;
  weathers: number[];
  routeType: number[];
  infoArr:string[];
}

const initWeatherConfig = (): WeatherConfig => {
  return {
    topLeft: {...initPoint},
    bottomRight: {...initPoint},
    interval: 3,
    forecast: 7,
    source: '1',
    resolution: 0.25,
    weathers: [],
    routeType: [],
    infoArr: ['1','2','3'],
  };
};


const STORAGE_NS = 'export_weather_config';
const getStorageKey = (stage?: TaskType | number | string) => `${STORAGE_NS}:${stage ?? 'default'}`;

const toConfigFromSaved = (base: WeatherConfig, saved: any): WeatherConfig => {
  const interval = Number(saved?.interval);
  const forecast = Number(saved?.forecast);
  const resolution = Number(saved?.resolution);
  const source = saved?.source != null ? String(saved?.source) : base.source;
  const weathers = Array.isArray(saved?.weathers)
      ? saved.weathers.map((x: any) => Number(x)).filter((x: any) => Number.isFinite(x))
      : base.weathers;
  const routeType = Array.isArray(saved?.routeType)
      ? saved.routeType.map((x: any) => Number(x)).filter((x: any) => Number.isFinite(x))
      : base.routeType;
  return {
    ...base,
    interval: Number.isFinite(interval) ? interval : base.interval,
    forecast: Number.isFinite(forecast) ? forecast : base.forecast,
    resolution: Number.isFinite(resolution) ? resolution : base.resolution,
    source,
    weathers,
    routeType,
  };
};

const applySavedConfig = (base: WeatherConfig, stage?: TaskType | number | string): WeatherConfig => {
  try {
    const stageKey = getStorageKey(stage);
    const rawStage = localStorage.getItem(stageKey);
    if (rawStage) {
      return toConfigFromSaved(base, JSON.parse(rawStage));
    }
    // 兼容旧版（未分阶段）存储，若存在则读取一次
    const rawLegacy = localStorage.getItem(STORAGE_NS);
    if (rawLegacy) {
      return toConfigFromSaved(base, JSON.parse(rawLegacy));
    }
    return base;
  } catch (e) {
    return base;
  }
};

const props = withDefaults(defineProps<Props>(), {});
const formRef = ref<FormInstance>();
const loading = ref(false);
const show = ref(false);
const form = reactive<WeatherConfig>(initWeatherConfig());

const infoOption = computed(() => {
  const arr = [
    { value: '1', label: '自主航线规划结果' },
    { value: '2', label: '航行安全评估结果' },
  ];
  // 当阶段为 1（出航准备）时，不显示第 3 项
  if (props.task?.taskStage !== 1) {
    arr.push({ value: '3', label: '航线周边气象水文预警' });
  }
  return arr;
});

const routeTypeOptions = computed(() => {
  const allowed = Array.isArray(props.task?.routeType) ? props.task?.routeType : [];
  const map = new Map(routeOptions.map(o => [o.value, o.label]));
  return allowed.map(v => ({ value: v, label: map.get(v) ?? String(v) }));
});

const rules = reactive<FormRules>({
  routeType: [
    { type: 'array', required: true, min: 1, message: '请至少选择一条航线', trigger: ['change'] },
  ],
  weathers: [
    { type: 'array', required: true, min: 1, message: '至少选择一项要素！', trigger: ['change'] },
  ],
  interval: [
    {required: true, message: '请选择时间分辨率', trigger: ['blur']},
  ],
  forecast: [
    {required: true, message: '请选择预报时效', trigger: ['blur']},
  ],
  source: [
    {required: true, message: '请选择数据源', trigger: ['blur']},
  ],
  resolution: [
    {required: true, message: '请选择空间分辨率', trigger: ['blur']},
  ],
});

const showDialog = () => {
  const base = initWeatherConfig();
  const withSaved = applySavedConfig(base, props.task?.taskStage);
  Object.assign(form, withSaved);
  // 过滤并默认全选：只显示/保存 props.routeType 中的航线；若当前为空则默认全选
  const allowedList = Array.isArray(props.task?.routeType) ? props.task?.routeType.slice() : [];
  if (allowedList.length) {
    const asSet = new Set(allowedList);
    const cur = Array.isArray(form.routeType) ? form.routeType.filter(v => asSet.has(v)) : [];
    form.routeType = cur.length ? cur : allowedList.slice();
  } else {
    form.routeType = [];
  }
  show.value = true;
  const topLeft = [props.task?.taskLtLongitude || 0, props.task?.taskLtLatitude || 0];
  const bottomRight = [props.task?.taskRbLongitude || 0, props.task?.taskRbLatitude || 0];
  const [tlLonDegree, tlLonMinute, tlLonSecond, tlLonDir] = lonBreakDown(topLeft[0]);
  const [tlLatDegree, tlLatMinute, tlLatSecond, tlLatDir] = latBreakDown(topLeft[1]);
  form.topLeft = {
    lonDir: tlLonDir, latDir: tlLatDir,
    latDegree: String(tlLatDegree), lonDegree: String(tlLonDegree),
    latMinute: String(tlLatMinute), lonMinute: String(tlLonMinute),
    latSecond: String(tlLatSecond), lonSecond: String(tlLonSecond),
  };
  const [brLonDegree, brLonMinute, brLonSecond, brLonDir] = lonBreakDown(bottomRight[0]);
  const [brLatDegree, brLatMinute, brLatSecond, brLatDir] = latBreakDown(bottomRight[1]);
  form.bottomRight = {
    lonDir: brLonDir, latDir: brLatDir,
    latDegree: String(brLatDegree), lonDegree: String(brLonDegree),
    latMinute: String(brLatMinute), lonMinute: String(brLonMinute),
    latSecond: String(brLatSecond), lonSecond: String(brLonSecond),
  };
};

const handleSaveEdit = async () => {
  const valid = await formRef.value?.validate();
  if (!valid) {
    return;
  }
  loading.value = true;
  try {
    let formData = {
      taskId: props.task?.id,
      meteos: form.weathers,
      resolution: form.resolution,
      hour: form.interval,
      day: form.forecast,
      source: form.source,
      routes: form.routeType,
    }

    const {code,data,message} = await getTaskPack(formData)

    if (!data) {
      ElMessage.error(message || '导出失败');
      loading.value = false;
      return;
    }

    // 拼接完整地址（默认使用 http 协议）
    const fullUrl = data?.download_url.startsWith('http')
        ? data?.download_url
        : `/node${data?.download_url.startsWith('/') ? data?.download_url : `/${data?.download_url}`}`;

    // 触发浏览器下载
    const a = document.createElement('a');
    a.href = fullUrl;
    a.setAttribute('download', '');
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    loading.value = false;
    show.value = false;

    saveConfig(form)

    ElMessage({
      type: 'success',
      message: '导出成功',
    });
  } catch (err: any) {
    console.log(err);
    loading.value = false;
    ElMessage({
      type: 'warning',
      message: err,
    });
  }
};

// 保存本次选择到 localStorage，便于下次自动填充
const saveConfig = (form: WeatherConfig) => {
  try {
    const persist = {
      interval: form.interval,
      forecast: form.forecast,
      source: form.source,
      resolution: form.resolution,
      weathers: Array.isArray(form.weathers) ? form.weathers : [],
      routeType: Array.isArray(form.routeType) ? form.routeType : [],
    };
    const stageKey = getStorageKey(props.task?.taskStage);
    localStorage.setItem(stageKey, JSON.stringify(persist));
  } catch (e) {
    console.warn('保存配置失败', e);
  }
}

const handleCancelEdit = () => {
  show.value = false;
};

defineExpose({showDialog});
</script>

<template>
  <ElDialog
      :class="['custom-dialog', 'region-edit-dialog']"
      v-model="show"
      :title="`${props.task?.name || '--'} - 导航图打包`"
      width="650px"
      :modal="true"
      :close-on-click-modal="false"
      @close="() => handleCancelEdit()"
  >
    <ElForm ref="formRef" class="weather-select-form" :model="form" :rules="rules" style="padding-right: 16px;"
            label-position="left">


      <ElFormItem label="任务信息" required>
        <ElCheckboxGroup v-model="form.infoArr">
          <ElCheckbox
              v-for="option in infoOption"
              :key="option.value"
              disabled
              :label="option.value"
              style="width: 120px;"
          >{{ option.label }}</ElCheckbox>
        </ElCheckboxGroup>
      </ElFormItem>

      <ElFormItem class="form-row" v-if="props.task?.taskStage !== 1">
        <ElFormItem prop="resolution" label="空间分辨率" style="width: 180px;">
          <ElSelect
              v-model="form.resolution"
              popper-class="custom-select-popper"
              :clearable="false"
          >
            <ElOption
                v-for="option in resolutionOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem prop="forecast" label="预报时效" style="width: 180px;">
          <ElSelect
              v-model="form.forecast"
              popper-class="custom-select-popper"
              :clearable="false"
          >
            <ElOption
                v-for="option in forecastOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem prop="source" label="数据源" style="width: 220px;">
          <ElSelect
              v-model="form.source"
              popper-class="custom-select-popper"
              :clearable="false"
          >
            <ElOption
                v-for="option in sourceOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem prop="interval" label="时间分辨率" style="width: 180px;">
          <ElSelect
              v-model="form.interval"
              popper-class="custom-select-popper"
              :clearable="false"
          >
            <ElOption
                v-for="option in intervalOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
            />
          </ElSelect>
        </ElFormItem>
      </ElFormItem>

      <ElFormItem prop="routeType" label="航线类型" required>
        <ElCheckboxGroup v-model="form.routeType">
          <ElCheckbox
              v-for="option in routeTypeOptions"
              :key="option.value"
              :label="option.value"
              style="width: 120px;"
          >{{ option.label }}</ElCheckbox>
        </ElCheckboxGroup>
      </ElFormItem>

      <template  v-if="props.task?.taskStage !== 1">
        <ElFormItem prop="weathers" label="打包要素" >
          <ElCheckboxGroup v-model="form.weathers">
            <ElCheckbox
                v-for="option in weatherOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
                style="width: 100px;"
            />
          </ElCheckboxGroup>
        </ElFormItem>

        <ElFormItem
            label="数据范围"
        >
          <span style="color: #FFFFFF" v-if="props.task?.taskStage === TaskType.outPrepare">航线左右侧5°范围</span>
          <span style="color: #FFFFFF"
                v-if="props.task?.taskStage === TaskType.warPrepare">航线左右侧5°范围,本舰周边15°✖15°范围</span>
          <span style="color: #FFFFFF" v-if="props.task?.taskStage === TaskType.warStart">
           任务区域范围 (
             {{ Math.abs(props.task.taskLtLatitude || 0) }}{{ (props.task.taskLtLatitude || 0) > 0 ? '°N' : '°S' }}
            {{ Math.abs(props.task.taskLtLongitude || 0) }}{{ (props.task.taskLtLongitude || 0) > 0 ? '°E' : '°W' }}
          ～
            {{ Math.abs(props.task.taskRbLatitude || 0) }}{{ (props.task.taskRbLatitude || 0) > 0 ? '°N' : '°S' }}
            {{ Math.abs(props.task.taskRbLongitude || 0) }}{{ (props.task.taskRbLongitude || 0) > 0 ? '°E' : '°W' }}

          )
        </span>
        </ElFormItem>
      </template>

      <ElFormItem
          label="包体大小"
      >
        <span style="color: #FFFFFF">暂定</span>
      </ElFormItem>
    </ElForm>
    <div class="dialog-footer">
      <ElButton @click="() => handleCancelEdit()">取消</ElButton>
      <ElButton
          :loading="loading"
          type="primary"
          @click="() => handleSaveEdit()"
      >确定
      </ElButton>
    </div>
  </ElDialog>
</template>

<style lang="less" scoped>
.weather-select-form {
  .form-row {
    > :deep(.el-form-item__content) {
      display: flex;
      flex-flow: row wrap;
      justify-content: space-between;
    }

    :deep(.el-form-item) {
      margin-bottom: 10px;
    }

    :deep(.el-form-item__label) {
      padding-right: 4px;
    }
  }
}
</style>
